package com.dushibao.manage.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.dushibao.entity.User;
import com.dushibao.service.UserService;
import com.dushibao.service.impl.UserServiceImpl;
import lombok.SneakyThrows;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@WebServlet("/uploadUserData")
public class UploadUserDataServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        req.setCharacterEncoding("UTF-8");

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 解析请求的内容提取文件数据
        List<FileItem> formItems = upload.parseRequest(req);
        FileItem item = formItems.get(0);

        XSSFWorkbook workbook = new XSSFWorkbook(item.getInputStream());
        XSSFSheet spreadsheet = workbook.getSheetAt(0);

        Iterator<Row> ite =  spreadsheet.rowIterator();
        List<User> users = new ArrayList<>();

        int i=0;
        while(ite.hasNext()){
            i++;
            Row row = ite.next();
            if(i == 1){
                continue;
            }
            CellType cellType = row.getCell(0).getCellType();
            System.out.println(cellType);
            Double id = row.getCell(0).getNumericCellValue();

            String addTime = row.getCell(1).getStringCellValue();
            String userName = row.getCell(2).getStringCellValue();
            String password = row.getCell(3).getStringCellValue();
            User user = new User();
            user.setId(id.longValue());
            user.setAddTime(LocalDateTimeUtil.parse(addTime,"yyyy-MM-dd HH:mm:ss"));
            user.setUserName(userName);
            user.setPassword(password);
            users.add(user);
        }

        if(CollUtil.isNotEmpty(users)){
            userService.saveBatch(users);
        }

        resp.getWriter().write("1000");
    }
}
